//
//  LoginViewController.swift
//  TestDemo
//
//  Created by 赵洋 on 2017/5/29.
//  Copyright © 2017年 赵洋. All rights reserved.
//

import UIKit
import MBProgressHUD
import Alamofire

class LoginViewController: UIViewController {
    
    @IBOutlet private weak var userNameTF: UITextField!
    
    @IBOutlet private weak var passwordTF: UITextField!
    
//MARK:  super
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true);
    }
    
  
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
    
//MARK: IBAction
    @IBAction func performUnwindSegue(segue:UIStoryboardSegue){
        if  segue.identifier == RegisterViewController.unwindSegue {
            let userInfo = (segue.source as! RegisterViewController).userInfo
            userNameTF.text = userInfo!["username"]
            passwordTF.text = userInfo!["password"]
        }
    }
    
    
    @IBAction func loginAction() {
      
        
        
        guard let username = userNameTF.text , username != "" else {
            MBProgressHUD.showErrorWith(text: "请输入用户名！")
            return
        }
        guard  let password = passwordTF.text , password != "" else {
            MBProgressHUD.showErrorWith(text: "请输入密码！")
            return
        }
        
        let parameter = ["username":username ,"pwd":password ,"device":"ios","login":"1","cx":"普通用户"]
        
        MBProgressHUD.showLoadingWith(Text: "请求中...")
        Alamofire.request("http://139.199.100.228/login.php", method: .post, parameters: parameter).responseJSON { [unowned self] response in
            
            MBProgressHUD.hideLoading()
            
            if let JSON = response.result.value ,let result = JSON as? [String:Int] ,let flag = result["flag"]{
                
                guard flag == 1 else {
                   MBProgressHUD.showErrorWith(text: "登录失败")
                    return
                }
                User.shareInstance.name = username
                User.shareInstance.password = password
                let userInfo = ["username":username , "password":password]
                UserDefaults.standard.set(userInfo, forKey: "userinfo")
                UserDefaults.standard.synchronize()
                self.navigationController?.dismiss(animated: true, completion: nil)
            }else{
                MBProgressHUD.showErrorWith(text: "网络异常")
            }
        }

    }
    

}
